{% extends 'base.html' %}

{% block title %}产品搜索 - 小原焊枪选型数据库{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="text-center mb-4 fade-in-up">
            <h1 class="display-5 fw-bold">
                <i class="bi bi-search me-3"></i>
                SERVO GUN 产品搜索
            </h1>
            <p class="lead text-muted">请选择分类并填写搜索条件</p>
        </div>
        
        <!-- AI智能搜索卡片 -->
        <div class="card mb-4 fade-in-up" style="border: 2px solid #007bff;">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">
                    <i class="bi bi-robot me-2"></i>
                    AI智能搜索(测试功能，欢迎试用，结果仅供参考)
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-9">
                        <label for="ai_query" class="form-label">
                            <i class="bi bi-chat-dots me-2"></i>
                            请用自然语言描述您的焊枪需求，AI将为您智能匹配合适的产品图号
                        </label>
                        <textarea class="form-control" id="ai_query" rows="1" style="resize: none;" 
                                placeholder="例如：喉深 300 左右，喉宽 450 左右，85 变压器，压力 4500 左右的 C 枪"></textarea>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="button" class="btn btn-primary w-100" id="ai_search_btn">
                            <i class="bi bi-magic me-2"></i>
                            AI智能搜索
                        </button>
                    </div>
                </div>
                
                <!-- AI搜索结果显示区域 -->
                <div id="ai_search_result" class="mt-3" style="display: none;">
                    <div class="alert alert-info">
                        <div id="ai_result_content"></div>
                        <div id="ai_result_actions" class="mt-2" style="display: none;">
                            <button type="button" class="btn btn-success" id="search_these_numbers">
                                <i class="bi bi-search me-2"></i>
                                搜索这些图号
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 加载状态 -->
                <div id="ai_search_loading" class="mt-3 text-center" style="display: none;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">正在搜索...</span>
                    </div>
                    <p class="mt-2 text-muted">AI正在分析您的需求，等待时间大约10秒，请稍候...</p>
                </div>
            </div>
        </div>
        
        <div class="card mb-4 fade-in-up" style="border: 2px solid #28a745;">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0">
                    <i class="bi bi-funnel me-2"></i>
                    常规搜索
                </h5>
            </div>
            <div class="card-body">
                <form method="get" action="{% url 'clamps:search_results' %}" id="searchForm">
                    {% csrf_token %}
                <!-- 主要搜索字段和图片预览 -->
                <div class="row g-3 mb-4">
                    <!-- 左侧两列：输入字段 -->
                    <div class="col-md-8">
                        <div class="row g-3">
                            <!-- 第一行 -->
                            <div class="col-md-6">
                                <label for="category" class="form-label">
                                    <i class="bi bi-diagram-3 me-2"></i>
                                    <span style="color: red; font-weight: bold;">产品分类</span> <span class="text-danger">*</span>
                                    <a href="/static/pdf/产品搜索使用指南.pdf" target="_blank" class="btn btn-outline-info btn-sm ms-2" title="使用指南">
                                        <i class="bi bi-question-circle"></i>
                                    </a>
                                </label>
                                <select class="form-select" id="category" name="category">
                                    <option value="">请选择，必选项</option>
                                    {% for category in categories %}
                                        {% if category.name in 'X2C-C,X2C-X' %}
                                            <option value="{{ category.id }}">{{ category.name }}(推荐)</option>
                                        {% else %}
                                            <option value="{{ category.id }}">{{ category.name }}</option>
                                        {% endif %}
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="sub_category_type" class="form-label"><i class="bi bi-tags me-2"></i>子分类类型</label>
                                <select class="form-select" id="sub_category_type" name="sub_category_type">
                                    <option value="">请选择，默认为空</option>
                                </select>
                            </div>

                            <!-- 第二行 -->
                            <div class="col-md-6">
                                <label for="throat_depth" class="form-label"><i class="bi bi-rulers me-2"></i>喉深</label>
                                <input type="text" class="form-control" id="throat_depth" name="throat_depth" placeholder="例如: ~350, 350~600, 600~">
                            </div>
                            <div class="col-md-6">
                                <label for="throat_width" class="form-label"><i class="bi bi-arrows-expand me-2"></i>喉宽</label>
                                <input type="text" class="form-control" id="throat_width" name="throat_width" placeholder="例如: ~350, 350~600, 600~">
                            </div>

                            <!-- 第三行 -->
                            <div class="col-md-6">
                                <label for="transformer" class="form-label"><i class="bi bi-cpu me-2"></i>变压器</label>
                                <select class="form-select" id="transformer" name="transformer">
                                    <option value="">请选择，默认为空</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="clamping_force" class="form-label"><i class="bi bi-lightning me-2"></i>加压力</label>
                                <input type="text" class="form-control" id="clamping_force" name="clamping_force" placeholder="例如: ~3500, 3500~5500, 5500~">
                            </div>
                        </div>
                    </div>

                    <!-- 右侧一列：图片显示区域 -->
                    <div class="col-md-4">
                        <div class="card h-100">
                            <div class="card-body text-center d-flex flex-column justify-content-center">
                                <h5 class="card-title">子分类选项预览图</h5>
                                <p class="text-muted small mb-2">预览图仅展示窗口样式，不考虑变压器方向与齿轮箱类型</p>
                                <img id="product_image" src="/static/images/No image available.png" alt="产品预览图" class="img-fluid" style="max-height: 250px;">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 高级搜索字段 -->
                <div class="mt-4">
                    <button class="btn btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#advancedSearch">
                        <i class="bi bi-gear me-2"></i>
                        高级搜索选项
                    </button>
                </div>
                
                <div class="collapse mt-3" id="advancedSearch">
                    <div class="card">
                        <div class="card-body">
                            <!-- 所有高级字段（静态+动态）都放在这个row里面 -->
                            <div class="row g-3" id="advanced-fields-container">
								<div class="col-md-4">
									<label for="drawing_no_1" class="form-label">
										<i class="bi bi-file-earmark-text me-2"></i>
										图号1(o)
									</label>
									<input type="text" class="form-control" id="drawing_no_1" name="drawing_no_1" 
										   placeholder="焊枪图号，默认为空">
								</div>
                                <div class="col-md-4">
                                    <label for="description" class="form-label"><i class="bi bi-card-text me-2"></i>描述</label>
                                    <input type="text" class="form-control" id="description" name="description" placeholder="客户描述，默认为空">
                                </div>
                                <div class="col-md-4">
                                    <label for="stroke" class="form-label"><i class="bi bi-arrows-move me-2"></i>行程</label>
                                    <input type="text" class="form-control" id="stroke" name="stroke" placeholder="例如: ~90, 100~190, 210~">
                                </div>
                                <div class="col-md-4">
                                    <label for="motor_manufacturer" class="form-label"><i class="bi bi-gear-wide-connected me-2"></i>MOTOR厂家</label>
                                    <select class="form-select" id="motor_manufacturer" name="motor_manufacturer">
                                        <option value="">请选择，默认为空</option>
                                        <option value="FANUC">FANUC</option>
                                        <option value="KUKA">KUKA</option>
                                        <option value="YASKAWA">YASKAWA</option>
                                        <option value="ABB">ABB</option>
                                        <option value="TOLOMATIC">TOLOMATIC</option>
                                        <option value="多摩川">多摩川</option>
                                        <option value="PANASONIC">PANASONIC</option>
                                        <option value="DIAKONT">DIAKONT</option>
                                        <option value="SEW">SEW</option>
                                        <option value="SANYO">SANYO</option>
                                        <option value="其他">其他</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="transformer_placement" class="form-label"><i class="bi bi-compass me-2"></i>变压器放置方向</label>
                                    <select class="form-select" id="transformer_placement" name="transformer_placement">
                                        <option value="">请选择，默认为空</option>
                                        <option value="水平">水平</option>
                                        <option value="竖直">竖直</option>
                                        <option value="下置">下置</option>
                                        <option value="上置">上置</option>
                                        <option value="右置">右置</option>
                                        <option value="其他">其他</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="has_balance" class="form-label"><i class="bi bi-water me-2"></i>有无平衡</label>
                                    <select class="form-select" id="has_balance" name="has_balance">
                                        <option value="">请选择，默认为空</option>
                                        <option value="有">有</option>
                                        <option value="无">无</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="weight" class="form-label"><i class="bi bi-box me-2"></i>重量</label>
                                    <input type="text" class="form-control" id="weight" name="weight" placeholder="例如: ~90, 90~120, 120~">
                                </div>
                                <div class="col-md-4">
                                    <label for="flange_pcd" class="form-label"><i class="bi bi-circle me-2"></i>法兰P.C.D</label>
                                    <select class="form-select" id="flange_pcd" name="flange_pcd">
                                        <option value="">请选择，默认为空</option>
                                        <option value="125">125</option>
                                        <option value="125-160">125-160</option>
                                        <option value="160">160</option>
                                        <option value="200">200</option>
                                        <option value="92">92</option>
                                        <option value="其他">其他</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="bracket_direction" class="form-label"><i class="bi bi-arrow-up-right me-2"></i>托架方向</label>
                                    <select class="form-select" id="bracket_direction" name="bracket_direction">
                                        <option value="">请选择，默认为空</option>
                                        <option value="右">右</option>
                                        <option value="上">上</option>
                                        <option value="前">前</option>
                                        <option value="下">下</option>
                                        <option value="后">后</option>
                                        <option value="三维">三维</option>
                                        <option value="左">左</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="water_circuit" class="form-label"><i class="bi bi-droplet me-2"></i>水路</label>
                                    <select class="form-select" id="water_circuit" name="water_circuit">
                                        <option value="">请选择，默认为空</option>
                                        <option value="1进1出">1进1出</option>
                                        <option value="2进2出">2进2出</option>
                                        <option value="3进3出">3进3出</option>
                                        <option value="1进2出">1进2出</option>
                                        <option value="2进3出">2进3出</option>
                                        <option value="1进3出">1进3出</option>
                                        <option value="其他">其他</option>
                                    </select>
                                </div>
                                
                                <!-- 动态字段将插入到这里 (关键改动) -->
                                <div id="dynamic-fields-placeholder" class="contents"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 搜索按钮 -->
                <div class="text-center mt-4">
                    <button type="submit" class="btn btn-primary btn-lg px-5" id="searchSubmitBtn">
                        <i class="bi bi-search me-2"></i>
                        开始搜索
                    </button>
                    <button type="reset" class="btn btn-outline-secondary btn-lg px-5 ms-3">
                        <i class="bi bi-arrow-clockwise me-2"></i>
                        重置条件
                    </button>
                </div>
                </form>
            </div>
        </div>
        
        <!-- 搜索提示 -->
        <div class="row mt-5">
		    <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-robot text-primary" style="font-size: 2rem;"></i>
                        <h5 class="card-title mt-3">AI智能搜索</h5>
                        <p class="card-text text-muted">使用自然语言描述需求，AI自动匹配合适的焊枪产品。</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-lightbulb text-warning" style="font-size: 2rem;"></i>
                        <h5 class="card-title mt-3">搜索提示</h5>
                        <p class="card-text text-muted">所有搜索条件都是可选的，留空表示不限制该条件。</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-funnel text-info" style="font-size: 2rem;"></i>
                        <h5 class="card-title mt-3">精确匹配</h5>
                        <p class="card-text text-muted">数字字段支持精确匹配，文本字段支持模糊搜索。</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-download text-success" style="font-size: 2rem;"></i>
                        <h5 class="card-title mt-3">文件下载</h5>
                        <p class="card-text text-muted">搜索结果中可直接下载PDF、STEP和ZIP文件。</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<style>
    /* 确保占位符本身不影响布局 */
    .contents {
        display: contents;
    }
</style>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const categorySubTypes = {
            'X2C-C(推荐)': ['大型', '特殊', '仙鹤型', '中小型'],
            'X2C-V2-C': ['大型', '特殊', '仙鹤型', '中小型'],
            'X2C-V3-C': ['大型', '小型'],
            'X2C-X(推荐)': ['大型', '特殊', '中小型', 'X', 'Y'],
            'X2C-V2-X': ['大型', '特殊', '小型', '中型', 'X', 'Y'],
            'X2C-V3-X': ['大型', '小型']
        };

        const categoryTransformerTypes = {
            'X2C-C(推荐)': ['ITS85', 'DB6-100R1', 'RT552', 'RT752','RT906', 'NI110',  'BOSCH', '商科', 'DB6-90-510', 'RT452', 'RT706','DB6-225-510(B)', '其他'],
            'X2C-V2-C': ['DB6','其他'],
            'X2C-V3-C': ['ITS85','SMF-100', 'MF-100','DB6-90', 'DB6-100', 'BOSCH', '商科', '其他'],
            'X2C-X(推荐)': ['ITS85', 'DB6-100R1', 'RT552', 'RT752','RT906', 'NI110',  'BOSCH', '商科', 'DB6-90-510', 'RT452', 'RT706','DB6-225-510(B)', '其他'],
            'X2C-V2-X': ['DB6','其他'],
            'X2C-V3-X': ['ITS85','SMF-100', 'MF-100','DB6-90', 'DB6-100', 'BOSCH', '商科', '其他']
        };
        
        // 缓存DOM元素
        const dynamicFieldsPlaceholder = document.getElementById('dynamic-fields-placeholder');
        let currentDynamicFields = [];

        function formatTransformerDisplayText(type) {
            if (type === 'ITS85' || type === 'DB6-100R1') return type + '(推荐)';
            if (type === 'DB6-90-510' || type === 'DB6' || type === 'DB6-90') return 'DB6-90';
            return type;
        }

        function updateTransformerOptions(categoryName) {
            const transformerSelect = document.getElementById('transformer');
            transformerSelect.innerHTML = '<option value="">请选择，默认为空</option>';
            if (categoryName && categoryTransformerTypes[categoryName]) {
                categoryTransformerTypes[categoryName].forEach(transformerType => {
                    const option = document.createElement('option');
                    option.value = transformerType;
                    option.textContent = formatTransformerDisplayText(transformerType);
                    transformerSelect.appendChild(option);
                });
            }
        }

        // 更新动态字段 (关键改动)
        function updateDynamicFields(categoryName) {
            // 1. 清除之前添加的动态字段
            currentDynamicFields.forEach(field => field.remove());
            currentDynamicFields = [];

            let fieldsToCreate = [];
            
            if (categoryName && categoryName.includes('-C')) {
                fieldsToCreate.push(
                    {
                        id: 'electrode_arm_end',
                        label: '电极臂端部',
                        type: 'select',
                        options: [
                            { value: '', text: '请选择，默认为空' },
                            { value: '握杆（铝）', text: '握杆（铝）' },
                            { value: 'TIP BASE（F 型）', text: 'TIP BASE（F 型）' },
                            { value: '握杆（SBA）', text: '握杆（SBA）' },
                            { value: 'TIP BASE（G 型）', text: 'TIP BASE（G 型）' },
                            { value: 'GUN HEAD（?36）', text: 'GUN HEAD（?36）' },
                            { value: 'GUN HEAD（?45）', text: 'GUN HEAD（?45）' },
                            { value: 'GUN HEAD（?40）', text: 'GUN HEAD（?40）' },
                            { value: 'GUN HEAD（?50）', text: 'GUN HEAD（?50）' },
                            { value: 'GUN HEAD（?60）', text: 'GUN HEAD（?60）' },
                            { value: '握杆?45（铝）', text: '握杆?45（铝）' },
                            { value: '握杆?50（铝）', text: '握杆?50（铝）' },
                            { value: '特殊', text: '特殊' },
                            { value: '其他', text: '其他' }
                        ]
                    },
					{
                        id: 'eccentricity',
                        label: '偏心距离',
                        icon: 'bi-arrows-angle-contract',
                        placeholder: '例如: 10~50, 50~'
                    }
                );
            } else if (categoryName && categoryName.includes('-X')) {
                fieldsToCreate = [
                    { id: 'static_arm_front_length', label: '静电极臂前部长', icon: 'bi-arrows-expand', placeholder: '例如: ~246, 246~346, 346~' },
                    { id: 'static_arm_front_height', label: '静电极臂前部高', icon: 'bi-arrows-vertical', placeholder: '例如: ~50, 50~100, 100~' },
                    { id: 'moving_arm_front_length', label: '动电极臂前部长', icon: 'bi-arrows-expand', placeholder: '例如: ~246, 246~346, 346~' },
                    { id: 'moving_arm_front_height', label: '动电极臂前部高', icon: 'bi-arrows-vertical', placeholder: '例如: ~50, 50~100, 100~' }
                ];
            }

            // 2. 创建并插入新的动态字段
            fieldsToCreate.forEach(field => {
                const fieldDiv = document.createElement('div');
                fieldDiv.className = 'col-md-4';
                
                if (field.type === 'select') {
                    let optionsHtml = field.options.map(option => 
                        `<option value="${option.value}">${option.text}</option>`
                    ).join('');
                    
                    fieldDiv.innerHTML = `
                        <label for="${field.id}" class="form-label">
                            <i class="bi ${field.icon || 'bi-tools'} me-2"></i>
                            ${field.label}
                        </label>
                        <select class="form-select" id="${field.id}" name="${field.id}">
                            ${optionsHtml}
                        </select>
                    `;
                } else {
                    fieldDiv.innerHTML = `
                        <label for="${field.id}" class="form-label">
                            <i class="bi ${field.icon} me-2"></i>
                            ${field.label}
                        </label>
                        <input type="text" class="form-control" id="${field.id}" name="${field.id}" placeholder="${field.placeholder}">
                    `;
                }
                
                // 将新字段插入到占位符之前，这样它们就会出现在占位符的位置
                dynamicFieldsPlaceholder.parentNode.insertBefore(fieldDiv, dynamicFieldsPlaceholder);
                currentDynamicFields.push(fieldDiv); // 保存对新字段的引用，以便后续清除
            });
        }

        const defaultImagePath = '/static/images/No image available.png';
        const productImageElement = document.getElementById('product_image');

        document.querySelector('button[type="reset"]').addEventListener('click', function() {
            document.getElementById('searchForm').reset();
            document.querySelectorAll('select').forEach(select => { select.selectedIndex = 0; });
            updateSubCategoryOptions('');
            updateTransformerOptions('');
            updateDynamicFields('');
            productImageElement.src = defaultImagePath;
        });
        
        document.getElementById('category').addEventListener('change', function() {
            const selectedText = this.options[this.selectedIndex].text;
            if (selectedText && selectedText !== '请选择，可为空') {
                updateSubCategoryOptions(selectedText);
                updateTransformerOptions(selectedText);
                updateDynamicFields(selectedText);
                updateProductImage();
            } else {
                updateSubCategoryOptions('');
                updateTransformerOptions('');
                updateDynamicFields('');
                productImageElement.src = defaultImagePath;
            }
        });

        document.getElementById('sub_category_type').addEventListener('change', function() {
            updateProductImage();
        });
        
        function updateSubCategoryOptions(categoryName) {
            const subCategorySelect = document.getElementById('sub_category_type');
            subCategorySelect.innerHTML = '<option value="">请选择，默认为空</option>';
            if (categoryName && categorySubTypes[categoryName]) {
                categorySubTypes[categoryName].forEach(subType => {
                    const option = document.createElement('option');
                    option.value = subType;
                    option.textContent = subType;
                    subCategorySelect.appendChild(option);
                });
            }
        }

        function updateProductImage() {
            const categorySelect = document.getElementById('category');
            const subCategorySelect = document.getElementById('sub_category_type');
            const selectedCategoryText = categorySelect.options[categorySelect.selectedIndex].text;
            const selectedSubCategoryText = subCategorySelect.options[subCategorySelect.selectedIndex].text;

            if (selectedCategoryText && selectedSubCategoryText && selectedSubCategoryText !== '请选择，默认为空') {
                const imageName = `${selectedCategoryText}-${selectedSubCategoryText}.png`;
                const imagePath = `/static/images/${imageName}`;
                const img = new Image();
                img.onload = () => { productImageElement.src = imagePath; };
                img.onerror = () => { productImageElement.src = defaultImagePath; };
                img.src = imagePath;
            } else {
                productImageElement.src = defaultImagePath;
            }
        }

        // 初始化
        const initialCategorySelect = document.getElementById("category");
        const initialCategoryText = initialCategorySelect.options[initialCategorySelect.selectedIndex].text;
        if (initialCategoryText && initialCategoryText !== '请选择，必选项') {
            updateSubCategoryOptions(initialCategoryText);
            updateTransformerOptions(initialCategoryText);
            updateDynamicFields(initialCategoryText);
            updateProductImage();
        } else {
            updateSubCategoryOptions('');
            updateTransformerOptions('');
            updateDynamicFields('');
            productImageElement.src = defaultImagePath;
        }
        // 页面加载完成后，如果尚未选择分类，则聚焦
        if (!document.getElementById('category').value) {
            document.getElementById('category').focus();
        }

        // AI搜索功能
        document.getElementById('ai_search_btn').addEventListener('click', function() {
            const query = document.getElementById('ai_query').value.trim();
            if (!query) {
                alert('请输入您的需求描述');
                return;
            }
            
            // 显示加载状态
            document.getElementById('ai_search_loading').style.display = 'block';
            document.getElementById('ai_search_result').style.display = 'none';
            
            // 发送AJAX请求
            fetch('/api/ai_search/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({
                    query: query
                })
            })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载状态
                document.getElementById('ai_search_loading').style.display = 'none';
                
                if (data.success) {
                    // 显示结果
                    const resultContent = document.getElementById('ai_result_content');
                    const resultActions = document.getElementById('ai_result_actions');
                    
                    if (data.data === '未找到符合要求的焊枪') {
                        resultContent.innerHTML = '<strong>搜索结果：</strong>' + data.data + '<br><small class="text-muted">建议您调整搜索条件后重试</small>';
                        resultActions.style.display = 'none';
                    } else {
                        resultContent.innerHTML = '<strong>找到以下图号：</strong><br>' + data.data;
                        resultActions.style.display = 'block';
                        
                        // 存储图号数据供后续使用
                        document.getElementById('search_these_numbers').setAttribute('data-numbers', data.data);
                    }
                    
                    document.getElementById('ai_search_result').style.display = 'block';
                } else {
                    alert('搜索失败：' + data.error);
                }
            })
            .catch(error => {
                document.getElementById('ai_search_loading').style.display = 'none';
                alert('网络错误，请稍后重试');
                console.error('Error:', error);
            });
        });
        
        // "搜索这些图号"按钮功能
        document.getElementById('search_these_numbers').addEventListener('click', function() {
            const numbers = this.getAttribute('data-numbers');
            if (numbers) {
                // 清空所有搜索条件
                document.getElementById('searchForm').reset();
                
                // 将图号填入图号1字段
                document.getElementById('drawing_no_1').value = numbers;
                
                // 提交表单
                document.getElementById('searchForm').submit();
            }
        });

        // 表单提交验证
        document.getElementById('searchForm').addEventListener('submit', function(event) {
            const categoryValue = document.getElementById('category').value;
            const drawingNo1Value = document.getElementById('drawing_no_1').value.trim();

            if (!categoryValue && !drawingNo1Value) {
                event.preventDefault(); // 阻止表单提交
                alert('产品分类为必选项，请选择！');
                location.reload(); // 页面刷新
            }
        });
    });
</script>
{% endblock %}